package com.sa.app.utilities;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.sa.app.R;
import com.sa.app.activities.MainActivity;

public class AsynchronousDownloaderXML extends
AsyncTask<String, Float, Integer> {

	private DataBaseManager dbm;
	private ProgressDialog progressDialog;
	private File temp;
	private String NFCID;
	private String manufacturer;
	private String[] links;
	private Context cont;
	private MainActivity ma;
	private Boolean networkError = false;

	public AsynchronousDownloaderXML(MainActivity ma, Context c,
			DataBaseManager dbm, String NFCID, String manufacturer, String model) {
		this.cont = c;
		this.ma = ma;
		this.dbm = dbm;
		this.NFCID = NFCID;
		this.manufacturer = manufacturer;
		progressDialog = new ProgressDialog(c);
		progressDialog.setTitle(manufacturer + " " + model);
		progressDialog.setMessage(ma.getString(R.string.downloading));

		temp = new File(cont.getFilesDir().getAbsolutePath() + "cache.xml");

	}

	protected void onPreExecute() {

		progressDialog.show();
	}

	protected Integer doInBackground(String... urls) {
		this.links = urls;

		Integer res = 1;
		try {

			URL miUrl = new URL(urls[0]);

			// Se crea la conexi�n http
			HttpURLConnection conn = (HttpURLConnection) miUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();

			// Se lee el stream de datos del XML
			InputStream in = conn.getInputStream();
			OutputStream out = new FileOutputStream(temp);

			byte[] buf = new byte[1024];
			int len;

			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}

			in.close();
			out.close();

		} catch (IOException e) {
			Log.i("Error en downloadXML",
					"�Hay conexi�n a internet?�La url es correcta, "
							+ urls[0] + "?");

			res = -1;
			networkError = true;

			e.printStackTrace();
		}

		return res;
	}

	protected void onProgressUpdate(Float... valores) {

	}

	protected void onPostExecute(Integer bytes) {

		String my = ma.getString(R.string.my);
		String aliasID = my + " " + manufacturer + " (1)";

		while (dbm.isThereAliasID(aliasID)) {

			String[] sa = aliasID.split(" ");
			String num = sa[sa.length - 1].substring(1, sa.length - 1);
			Integer i = Integer.valueOf(num);
			i++;
			aliasID = my + " " + manufacturer + " (" + i + ")";
		}
		ItemXMLParser parser = new ItemXMLParserImpl(temp, NFCID, aliasID,
				links[0]);
		String imgUrl = parser.getItem().get(6);
		AsynchronousDownloaderImg aImg = new AsynchronousDownloaderImg(ma,
				cont, dbm, parser, NFCID, networkError);
		aImg.execute(imgUrl);
		progressDialog.dismiss();
	}
}
